package server

import (
	"github.com/gin-gonic/gin"
	"github.com/twwch/gin-sdk/handler"
	"github.com/twwch/gin-sdk/handler/test"
	"github.com/twwch/gin-sdk/server"
	"net/http"
	"twwch/k8s-admin/config"
	"twwch/k8s-admin/handlers"
	"twwch/k8s-admin/middleware/cors"
	"twwch/k8s-admin/middleware/jwt"
)

type HTTP struct {
	Server server.Server
}

var defaultHTTP Server = &HTTP{}

func (h *HTTP) New(address string) Server {
	return &HTTP{
		Server: newRouter(address),
	}
}

var httphandlers = []handler.Handler{
	&handlers.DeployHandler{},
	&handlers.NamespaceHandler{},
	&handlers.ServiceHandler{},
	&handlers.ConfigMapHandler{},
	&handlers.PodHandler{},
}

var noAuthHttphandlers = []handler.Handler{
	&test.TestHanlder{},
	&handlers.AuthHandler{},
}

func newRouter(address string) server.Server {
	conf := config.Get()
	httpServer := server.NewServer(server.Options{
		Name:    "K8S-ADMIN",
		Address: address,
		LogConf: &conf.LogConf,
	})

	router := httpServer.GetEngine()

	notAuthV1 := router.Group("/v1")
	{
		for _, hd := range noAuthHttphandlers {
			hd.Init(notAuthV1)
		}
		notAuthV1.GET("/conf", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "获取配置成功！",
				"data": config.Get(),
			})
		})
	}

	router.Use(cors.NewCors())
	router.Use(jwt.NewJwt())
	v1 := router.Group("/v1")
	{
		for _, hd := range httphandlers {
			hd.Init(v1)
		}
	}
	return httpServer
}
